//
//  ByViewIndexAdvert.m
//  jinpuyiyuan_ios
//
//  Created by mc on 2017/12/5.
//  Copyright © 2017年 mc. All rights reserved.
//

#import "ByViewIndexAdvert.h"
#define KImageViewBaseTag 10

@interface ByViewIndexAdvert()<UIScrollViewDelegate>
{
    // data
    NSInteger   _carouselAmount;    // 轮播数
    CGFloat     _duration;          // 轮播时间间隔
}
// view
@property (nonatomic, strong) UIScrollView              *scroll;        // 滑动视图
@property (nonatomic, strong) UIActivityIndicatorView   *activity;      // 等待视图

// 定时器
@property (nonatomic, strong) NSTimer                   *timer;

@end

@implementation ByViewIndexAdvert
- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}
// 初始化frame和轮播时间间隔
- (instancetype)initWithFrame:(CGRect)frame
                timerDuration:(CGFloat)duration {
    
    if (self = [super initWithFrame:frame]) {
        
        _duration = duration;
        
        // 未获得轮播视图时，先显示菊花转动，用作等待效果
        [self.activity startAnimating];
        
        // 开启定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:_duration target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    return self;
}

#pragma mark - 视图懒加载
// 等待视图
- (UIActivityIndicatorView *)activity {
    
    if (!_activity) {
        _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activity.center = CGPointMake(self.width / 2, self.height / 2);
        _activity.hidesWhenStopped = YES;
        [self addSubview:_activity];
    }
    return _activity;
}
// 滑动视图
- (UIScrollView *)scroll {
    if (!_scroll && _carouselAmount != 0) {
        _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        _scroll.contentSize = CGSizeMake(0, _scroll.height *(_carouselAmount + 2));
        _scroll.pagingEnabled = YES;
        _scroll.showsHorizontalScrollIndicator = NO;
        _scroll.delegate = self;
        
        for (int i = 0; i < _carouselAmount + 2; i ++) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, i *_scroll.height, _scroll.width, _scroll.height)];
            label.tag = KImageViewBaseTag + i;
            [_scroll addSubview:label];
            label.userInteractionEnabled = YES;
            label.font = FONT(14);
            label.adjustsFontSizeToFitWidth = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickViewAtIndex:)];
            [label addGestureRecognizer:tap];
        }
        _scroll.contentOffset = CGPointMake(0, _scroll.height);
        
        // 把滑动视图作为最底部的视图
        [self insertSubview:_scroll atIndex:0];
    }
    
    return _scroll;
}

#pragma mark - 滑动视图代理
// 滑动视图已经停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //如果已经滑动到最后一张，则跳到第二张
    if (self.scroll.contentOffset.y == (_carouselAmount + 1) * self.scroll.height) {
        self.scroll.contentOffset = CGPointMake(0, self.scroll.height);
    }
    //如果滑动到到第一张，则跳到倒数第二张
    else if (self.scroll.contentOffset.y == 0) {
        self.scroll.contentOffset = CGPointMake( 0,_carouselAmount * self.scroll.height);
    }
}


#pragma mark - 定时器方法
// 定时器方法
- (void)timerAction:(NSTimer *)timer {
    // 如果还未创建则跳过定时器方法
    if (!self.scroll) {
        return;
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.scroll.contentOffset = CGPointMake(0,self.scroll.contentOffset.y + self.scroll.height);
    }];
    // 如果已经滑动到最后一张，则跳到第二张
    if (self.scroll.contentOffset.y == (_carouselAmount + 1) * self.scroll.height) {
        self.scroll.contentOffset = CGPointMake(0,self.scroll.height);
    }
    // 如果滑动到到第一张，则跳到倒数第二张
    if (self.scroll.contentOffset.y == 0) {
        self.scroll.contentOffset = CGPointMake(0,_carouselAmount * self.scroll.height);
    }
}

#pragma mark - 点击事件
// 点击轮播的内容视图
- (void)clickViewAtIndex:(UITapGestureRecognizer *)tap {
    NSInteger tag = tap.view.tag;
    NSInteger tapIndex = tag - (KImageViewBaseTag + 1);
//    if (_models.count != 0) {
//        ByModelHomeNotice *model = _models[tapIndex];
//        if (model.notice_id.length != 0) {
//            if (self.pushBlock) {
//                self.pushBlock(model);
//            }
//
//        }
//    }
    
}

- (void)setModels:(NSArray *)models {
    _models = models;
    // 关闭等待效果
    [self.activity stopAnimating];
    
    // 如果没轮播图，则设置一张默认的图片，且不轮播
    if (models == nil || models.count == 0) {
    }
    else{
        // 给视图的图片URL字符串数组赋值
        NSMutableArray *temp = [NSMutableArray array];
        temp = [models mutableCopy];
        [temp addObject:models[0]];
        [temp insertObject:models[models.count - 1] atIndex:0];
        
        // 设置好轮播数组
        models = [temp copy];
        
        // 设置轮播数量
        _carouselAmount = models.count - 2;
        
        // 如果只有一张图片，则不轮播
        if (_carouselAmount == 1) {
            [self.timer invalidate];
            self.timer = nil;
            [self.scroll setScrollEnabled:NO];
        }
        
        // 给轮播图片视图设置从网上获取的图片
        for (int tag = KImageViewBaseTag; tag < KImageViewBaseTag + _carouselAmount + 2; tag ++) {
//            UILabel *titleLabel      = (UILabel *)[self.scroll viewWithTag:tag];
//            ByModelHomeNotice *model = models[tag - KImageViewBaseTag];
//            // 如果图片数组为空，则需要显示一张无数据的图片（注意，和默认图片是不同的）
//            if ([model.post_title isEqualToString:@""]) {
//                titleLabel.text = @"";
//            } else {
//                titleLabel.text = model.post_title;
//            }
        }
        
    }
    
    
}

@end
